package cn.laixueit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileUploadController {


    @PostMapping("/img")
    public ModelAndView uploadImg(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {

        String realPath = request.getSession().getServletContext().getRealPath("/img");
//
//        File dir = new File("D:\\codeSpace\\java209\\springmvc-08\\src\\main\\webapp\\img");
//        if(!dir.exists()){
//            dir.mkdirs();
//        }
        String filename = uuid()+ file.getOriginalFilename();

//        File f2 = new File(dir, filename);
//        file.transferTo(f2);

        File f = new File(realPath, filename);

//        FileUtils.copyFile(f2,f);
        file.transferTo(f);


        ModelAndView view = new ModelAndView();
        view.setViewName("test");
//        view.addObject("img",realPath+filename);
        view.addObject("img2",filename);

        return view;

    }

    private String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }
}
